import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
import { writeFileSync, copyFileSync, mkdirSync } from 'fs'

// 复制manifest和图标
function copyManifest() {
  return {
    name: 'copy-manifest',
    closeBundle() {
      // 确保目标目录存在
      mkdirSync('dist/icons', { recursive: true })
      
      // 复制manifest.json
      copyFileSync('manifest.json', 'dist/manifest.json')
      
      // 复制background.js
      copyFileSync(
        resolve(__dirname, 'src/background/background.js'),
        resolve(__dirname, 'dist/background.js')
      )
      
      // 复制图标
      const icons = ['16', '48', '128']
      icons.forEach(size => {
        copyFileSync(
          `public/icons/icon${size}.png`,
          `dist/icons/icon${size}.png`
        )
      })
    }
  }
}

export default defineConfig({
  plugins: [vue(), copyManifest()],
  build: {
    outDir: 'dist',
    assetsDir: 'assets',
    rollupOptions: {
      input: {
        popup: resolve(__dirname, 'src/popup/index.html')
      },
      output: {
        entryFileNames: '[name].js',
        chunkFileNames: 'chunks/[name].[hash].js',
        assetFileNames: (assetInfo) => {
          if (assetInfo.name === 'style.css') {
            return 'assets/[name].[hash].css'
          }
          return 'assets/[name].[hash].[ext]'
        }
      }
    }
  },
  resolve: {
    alias: {
      '@': resolve(__dirname, 'src')
    }
  }
}) 